package com.yuchen.ishop.web;

import com.yuchen.core.cache.J2CacheUtils;
import com.yuchen.ishop.Gobals;
import com.yuchen.ishop.entity.Dictionary;
import com.yuchen.ishop.service.CacheService;
import com.yuchen.ishop.service.dictionary.DictionaryRestClient;
import com.yuchen.utils.SpringContextUtils;
import com.yuchen.utils.config.ConfigUtils;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import java.util.List;


/**
 * @author Jack Q
 * Date: 13-6-6
 * Time: 下午3:52
 * 监听spring加载完成后，初始化配置
 */

public class SpringApplicationListener extends ContextLoaderListener {

    private final static Logger LOG = Logger.getLogger(SpringApplicationListener.class);

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        super.contextDestroyed(event);
    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
        super.contextInitialized(event);

        LOG.info("加载缓存初始化……");
        System.setProperty("java.net.preferIPv4Stack", "true"); //Disable IPv6 in JVM
        J2CacheUtils.init();

        ServletContext servletContext = event.getServletContext();
        String env = ConfigUtils.config.get("env");
        LOG.info("应用环境："+env);
        if("product".equals(env)){
            LOG.info("静态服务器地址:"+ConfigUtils.config.get("staticServerUrl"));
            servletContext.setAttribute("staticServerUrl", ConfigUtils.config.get("staticServerUrl")); //静态服务器地址
            servletContext.setAttribute("fileServerUrl", ConfigUtils.config.get("fileServerUrl")); //文件服务器地址
        }else{
            LOG.info("静态服务器地址:"+servletContext.getContextPath());
            servletContext.setAttribute("staticServerUrl", servletContext.getContextPath()); //静态服务器地址
            servletContext.setAttribute("fileServerUrl", ConfigUtils.config.get("fileServerUrl")); //文件服务器地址
        }

        LOG.info("设置ApplicationContext……");
        ApplicationContext context = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        SpringContextUtils.me(context);
        LOG.info("初始化完成……");


        LOG.info("加载系统商品类型……");
        CacheService cacheService = SpringContextUtils.getBean(CacheService.class);
        cacheService.setDictionaryCache();
        LOG.info("加载系统商品类型完成……");

        LOG.info("加载地址信息……");
        cacheService.setAddressCache();
        LOG.info("加载地址信息完成……");


    }




}
